#include "FieldValidator.h"

#include <QLineEdit>

FieldValidator::FieldValidator(QWidget *parent) :
    QWidget(parent)
{
    button = nullptr;
    formValid = false;
}

void FieldValidator::addAllFields()
{
    // Get list of all line edit fields
    QList<QLineEdit *> lineEditList = parent()->findChildren<QLineEdit *>();

    // Connect each field's change signal to the check_fields slot so that the
    // form is checked every time a field is edited
    for (int i = 0; i < lineEditList.size(); i++)
    {
        connect(lineEditList.at(i), SIGNAL(textChanged(QString)), this, SLOT(check_fields(QString)));
        widgetList.push_back(lineEditList.at(i));
    }
}

void FieldValidator::setButton(QPushButton *button)
{
    this->button = button;
}

void FieldValidator::resetFields()
{
    for(int i = 0; i < widgetList.size(); i++)
    {
        QLineEdit * field = widgetList.at(i);

        field->clear();
        field->setStyleSheet("");
    }
}

void FieldValidator::check_fields(QString)
{
    bool isValid = true;

    for(int i = 0; i < widgetList.size(); i++)
    {
        QLineEdit * field = widgetList.at(i);
        if (field->text().isEmpty())
        {
            isValid = false;
            field->setStyleSheet("QLineEdit{background: #ffdddd}");
        }
        else
            field->setStyleSheet("");
    }

    if (button != nullptr)
    {
        if (isValid != formValid)
        {
            button->setEnabled(isValid);
            formValid = isValid;
        }
    }
}
